package com.lwh.jxl.controller;



import com.lwh.jxl.entity.AdCheliangEntity;
import com.lwh.jxl.service.AdCheliangService;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;


/**
 * @Title: Controller
 * @Description: 车辆管理
 * @author
 * @date
 * @version
 *
 */
@Controller
@RequestMapping("/adCheliang")
public class AdCheliangController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(AdCheliangController.class);

	@Autowired
	private AdCheliangService adCheliangService;

	// 查询页面内容
	@RequestMapping("/findPage")
	@ResponseBody
	public Callable<Map<String,Object>> findPage(AdCheliangEntity query){

		if(query.getPage()==null) {
			query.setPage(1);
		}
		if(query.getRows()==null) {
			query.setRows(10);
		}
		Callable<Map<String,Object>> callable =(()->adCheliangService.findPage(query));
		return callable;
	}

	/**
	 * 增加功能
	 * @param
	 * @return
	 */
	@PostMapping("/addCheliang")
	@ResponseBody
	public Callable<String> add(AdCheliangEntity AdCheliangEntity){

		Callable<String> callable =null;

		try {
			adCheliangService.insertSelective(AdCheliangEntity);
			callable = ()->{return "success";};
		} catch (Exception e) {
			e.printStackTrace();
			callable = ()->{return "系统出错了";};
		}
		return callable;
	}

    // 修改
	@PostMapping("/updateCheliang")
	@ResponseBody
	public Callable<String> update(AdCheliangEntity adCheliangEntity){

		Callable<String> callable =null;
		if(adCheliangEntity.getId() == null) {
			callable = ()->{return "系统缺少参数";};
			return callable;
		}
		try {
			callable = ()->{
				adCheliangService.updateByPrimaryKeySelective(adCheliangEntity);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = ()->{return "系统发生错误";};
		}
		return callable;
	}



	// 批量删除
	@RequestMapping("/deleteCheliang")
	@ResponseBody
	public Callable<String> delete(String[] ids){
		Callable<String> callable =null;
		if(ids == null || ids.length==0) {
			callable = ()->{return "系统缺少参数";};
			return callable;
		}
		try {
			callable = ()->{
				adCheliangService.deleteByIds(ids);
				return "success";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = ()->{return "系统发生错误";};
		}
		return callable;
	}

	// 单独删除
	@RequestMapping("/deleteOneCheliang")
	@ResponseBody
	public Callable<String> deleteOne(String id){
		Callable<String> callable =null;
		if(id == null ) {
			callable = ()->{return "系统缺少参数";};
			return callable;
		}
		try {
			callable = ()->{
				adCheliangService.deleteOneById(id);
				return "删除成功";
			};
		} catch (Exception e) {
			e.printStackTrace();
			callable = ()->{return "系统发生错误";};
		}
		return callable;
	}

	// 导入
	@RequestMapping("/importExcel")
	@ResponseBody
	public String importExcel(MultipartFile uploadFile){

		String result = adCheliangService.importExcel(uploadFile);

		return result;

	}

	// 导出
	@RequestMapping("/exportExcel")
	@ResponseBody
	public String outExcel(AdCheliangEntity adCheliangEntity,HttpServletResponse response) throws Exception{

		// 1.文件下载响应头
		response.setHeader("Content-Disposition", "attachment;filename="+new String("车辆管理.xls".getBytes("gb2312"), "ISO8859-1"));
		// 2.响应到浏览器
		WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());

		List<AdCheliangEntity> list = adCheliangService.outExcel(adCheliangEntity);
		if(list != null && list.size()>0){
			try{

				//FileOutputStream out = new FileOutputStream(f);
				// 指定导出数据的路径
				Long time = new Date().getTime();
				String filepath ="//OweMaterial";
				File fpath = new File(filepath);
				fpath.mkdir();
				String filename = "车辆管理"+".xls";
				File f = new File(filename);
				if(!f.exists()){
					f.createNewFile();
				}
				OutputStream out = new FileOutputStream(f);
				/** **********创建工作簿************ */
				WritableWorkbook wwb = Workbook.createWorkbook(out);
				//创建Excel工作表 指定名称和位置
				WritableSheet ws = wwb.createSheet("车辆管理",0);

				/** ************设置单元格字体************** */
				WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
				WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);

				/** ************以下设置单元格样式************ */
				// 用于标题居中
				WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
				wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
				wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
				wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
				wcf_center.setWrap(false); // 文字是否换行

				// 用于正文居左
				WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
				wcf_left.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
				wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
				wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
				wcf_left.setWrap(false); // 文字是否换行

				// 汇总表表头
				String[] summTitils = new String[]{
						"车牌号","车型","最大体积","载重","载人数","准假驾照","是否可用"
						,"备注","默认司机","gps","区域"};

				// 显示汇总表
				for (int i = 0; i < summTitils.length; i++) {
					ws.addCell(new Label(i, 0,summTitils[i],wcf_center));
				}
				int i = 1; // excel 行号
				for(AdCheliangEntity ad:list)
				{
					ws.addCell(new Label(0, i, ad.getChepaihao(),wcf_left));
					ws.addCell(new Label(1, i, ad.getChexing(),wcf_left));
					ws.addCell(new Label(2, i, ad.getZuidatiji(),wcf_left));
					ws.addCell(new Label(3, i, ad.getZaizhong(),wcf_left));
					ws.addCell(new Label(4, i, ad.getZairen(),wcf_left));
					ws.addCell(new Label(5, i, ad.getJiazhao(),wcf_left));
					ws.addCell(new Label(6, i, ad.getZhuangtai(),wcf_left));
					ws.addCell(new Label(7, i, ad.getBeizhu(),wcf_left));
					ws.addCell(new Label(8, i, ad.getUsername(),wcf_left));
					ws.addCell(new Label(9, i, ad.getGpsid(),wcf_left));
					ws.addCell(new Label(10, i, ad.getQuyu(),wcf_left));
					i++;

				}


				//写入工作表
				wwb.write();
				wwb.close();
				out.flush();
				out.close();
				String returnstr = "导出成功，文件已经生成。请查看"+filename;
				Runtime runtime=Runtime.getRuntime();
				try{
					runtime.exec("cmd /c start "+filename);
				}catch(Exception e){
					return  "导出失败";
				}
				return returnstr;
			}catch (Exception e) {
				return "导出失败";
			}
		}else{
			return  "没有任何要导出的数据";

		}

	}

	// 模板下载
	@RequestMapping("/modelExcel")
	@ResponseBody
	public String modelExcel(HttpServletResponse response) throws Exception{

		String fileName ="车辆信息.xls";
		//添加响应头信息
		response.setHeader("Content-disposition", "attachment; filename=" +  URLEncoder.encode(fileName,"UTF-8"));
		response.setContentType("application/msexcel;charset=UTF-8");//设置类型
		response.setHeader("Pragma", "No-cache");//设置头
		response.setHeader("Cache-Control", "no-cache");//设置头
		response.setDateHeader("Expires", 0);//设置日期头
		// 2.响应到浏览器
		WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());

		List<AdCheliangEntity> list = new ArrayList<>();
			try{
				//FileOutputStream out = new FileOutputStream(f);
				// 指定导出数据的路径
				Long time = new Date().getTime();
				String filepath ="//OweMaterial";
				File fpath = new File(filepath);
				fpath.mkdir();
				String filename = "车辆管理"+".xls";
				File f = new File(filename);
				if(!f.exists()){
					f.createNewFile();
				}
				OutputStream out = new FileOutputStream(f);
				/** **********创建工作簿************ */
				WritableWorkbook wwb = Workbook.createWorkbook(out);
				//创建Excel工作表 指定名称和位置
				WritableSheet ws = wwb.createSheet("车辆管理",0);

				/** ************设置单元格字体************** */
				WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
				WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10,WritableFont.BOLD);

				/** ************以下设置单元格样式************ */
				// 用于标题居中
				WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
				wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
				wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
				wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
				wcf_center.setWrap(false); // 文字是否换行

				// 用于正文居左
				WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
				wcf_left.setBorder(Border.ALL, BorderLineStyle.THIN); // 线条
				wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
				wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
				wcf_left.setWrap(false); // 文字是否换行

				// 汇总表表头
				String[] summTitils = new String[]{
						"车牌号","车型","最大体积","载重","载人数","准假驾照","是否可用"
						,"备注","默认司机","gps","区域"};

				// 显示汇总表
				for (int i = 0; i < summTitils.length; i++) {
					ws.addCell(new Label(i, 0,summTitils[i],wcf_center));
				}
				int i = 1; // excel 行号


				//写入工作表
				wwb.write();

				wwb.close();
				out.flush();
				out.close();
				String returnstr = "导出成功，文件已经生成。请查看"+filename;
				Runtime runtime=Runtime.getRuntime();
				try{
					runtime.exec("cmd /c start "+filename);
				}catch(Exception e){
					return  "导出失败";
				}
				return returnstr;
			}catch (Exception e) {
				return "导出失败";
			}

	}

}
